/*
 * Copyright (c) 2010 Olivier Van Acker
 *
 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 */

package org.transformatorhuis.unix.server;

import com.sun.jna.StringArray;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * User: Olivier Van Acker
 * Date: Mar 12, 2010
 */
public abstract class CommandLine extends ArrayList<String> {

    public CommandLine() throws Exception {
            
    }

    protected CommandLine(Collection<? extends String> c) {
        super(c);
    }

    public void removeSystemProperty(String property) {
        property = "-D" + property;
        String nameeq = property + '=';
        for (Iterator<String> itr = this.iterator(); itr.hasNext();) {
            String s =  itr.next();
            if(s.equals(property) || s.startsWith(nameeq))
                itr.remove();
        }
    }

    public void setSystemProperty(String name, String value) {
        removeSystemProperty(name);
        // index 0 is the executable name
        add(1,"-D" + name + "=" + value);   
    }

    /**
     * Removes the n items from the end.
     * Useful for removing all the Java arguments to rebuild them.
     */
    public void removeTail(int n) {
        removeAll(subList(size()-n,size()));
    }

    /*package*/ StringArray toStringArray() {
        return new StringArray(toArray(new String[size()]));
    }

}
